package controllers

import (
	"github.com/astaxie/beego"
	m"xmy/models/wechat"
	"fmt"
	"reflect"
	"qiniupkg.com/api.v7/kodo"
	"qiniupkg.com/api.v7/conf"
	"qiniupkg.com/api.v7/kodocli"

	"path/filepath"

	"os"
)

var (
	//设置上传到的空间
	bucket = "hfkj"
	//设置上传域名
	domain = "oanidcjtg.bkt.clouddn.com"
	//AK，SK
	ACCESS_KEY = "sYqcRJz3yFj_OxfZIDl5h3a_IY0VVBZKS9oZRG1s"
	SECRET_KEY = "Jt4jFLu_q4XekA5TMWupqyPYnqjYXCoH1VhfEvjV"
)

//构造返回值字段
type PutRet struct {
	Key string `json:"key"`
}
type WechatController struct {
	beego.Controller
}
//测试 接口
func (c *WechatController)  TestSql11() {
	maps := m.Test111()
	fmt.Println("TestSql................................", maps)

	fmt.Println("type:", reflect.TypeOf(maps))
	//c.Data["json"] = &map[string]interface{}{"data": &maps}
	data := make(map[string]interface{}, 2)
	data["status"] = 1//结果状态 告诉调用方成功失败
	data["data"] = maps//返回的数据 失败直接是空 成功返回相关数据 可以是任意类型的数据
	c.Data["json"] = data
	c.ServeJSON()
	//c.Ctx.WriteString("111")
	return
}

func (c *WechatController)  Home() {
	c.TplName = "home.html"

}

//图片上传
func (c *WechatController)  UpLoad() {
	//获取上传对象
	_, h, _ := c.GetFile("myfile")
	imgPath := "static/images/" + h.Filename
	c.SaveToFile("myfile", imgPath)
	//初始化AK，SK
	conf.ACCESS_KEY = ACCESS_KEY
	conf.SECRET_KEY = SECRET_KEY
	//创建一个Client
	d := kodo.New(0, nil)
	//设置上传的策略
	policy := &kodo.PutPolicy{
		Scope:   bucket,
		//设置Token过期时间
		Expires: 3600,
	}
	//生成一个上传token
	token := d.MakeUptoken(policy)
	//构建一个uploader
	zone := 0
	uploader := kodocli.NewUploader(zone, nil)
	var ret PutRet
	file := imgPath
	key := filepath.Base(file)
	res := uploader.PutFile(nil, &ret, token, key, file, nil)
	//打印出错信息
	if res != nil {
		fmt.Println("io.Put failed:", res)
		return
	}
	println(downloadUrl(domain, key))
	imgUrl := downloadUrl(domain, key)
	count := m.SaveImgUrl(imgUrl)
	if count > 0 {
		//图片地址存入数据库之后删除该图片
		os.RemoveAll(imgPath)
		fmt.Println("上传图片成功")
		return
	} else {

		return
	}
	return

}

//下载图片获取地址
func downloadUrl(domain, key string) string {
	//调用MakeBaseUrl()方法将domain,key处理成http://domain/key的形式
	baseUrl := kodo.MakeBaseUrl(domain, key)
	policy := kodo.GetPolicy{}
	//生成一个client对象
	c := kodo.New(0, nil)
	//调用MakePrivateUrl方法返回url
	return c.MakePrivateUrl(baseUrl, &policy)
}


func (c *WechatController)  Index() {
	c.TplName = "wechat/index.html"

}